package util;

import java.io.*;
import java.util.Base64;

/**
 * User: tum0r
 * Package Name: util
 * Time: 2019-03-16 Saturday 15:17:38
 */
public class FileConvert {

    public String fileToHex(String path) throws IOException {
        return fileToHex(new File(path));
    }

    public String fileToHex(File file) throws IOException {
        StringBuilder result = new StringBuilder();
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] data = new byte[1024];
        int count = 0;
        String temp;
        while ((count = fileInputStream.read(data)) != -1) {
            for (int i = 0; i < count; i++) {
                temp = Integer.toHexString(data[i] & 0xff);
                if (temp.length() == 1) {
                    result.append("0");
                }
                result.append(temp);
            }
        }
        fileInputStream.close();
        return result.toString();
    }

    public byte[] hexToBytes(String hex) {
        byte[] data;
        if (hex == null || hex.equals("") || hex.length() % 2 != 0) {
            data = new byte[0];
        } else {
            int length = hex.length();
            data = new byte[length / 2];
            for (int i = 0; i < length; i += 2) {
                data[i / 2] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
            }
        }
        return data;
    }

    public String hexToBase64(String hex){
        return "data:image;base64," +  Base64.getEncoder().encodeToString(hexToBytes(hex)).trim();
    }

    public File hexToFile(String hex) throws IOException {
        File file = new File("");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(hexToBytes(hex));
        fileOutputStream.close();
        return file;
    }

    public String getFileHash(String fileContent){
        return getFileHash(fileContent,Hash.SHA256);
    }
    public String getFileHash(String fileContent,String mode){
        Hash hash = new Hash();
        return hash.encryption(fileContent,mode);
    }
}
